use tauri::{ipc::Channel, AppHandle};
use tauri_plugin_updater::{Error, UpdaterExt};

#[tauri::command]
pub async fn check_update(app: AppHandle) -> Result<bool, Error> {
    log::info!("checking for update");
    match app.updater() {
        Err(e) => Err(e),
        Ok(update) => match update.check().await {
            Err(e) => Err(e),
            Ok(_) => {
                log::info!("update found");
                return Ok(true);
            }
        },
    }
}

#[tauri::command]
pub async fn download(app: AppHandle, on_event: Channel<u64>) -> Result<(), String> {
    let update = match app.updater() {
        Err(e) => return Err(e.to_string()),
        Ok(update) => match update.check().await {
            Err(e) => return Err(e.to_string()),
            Ok(v) => v,
        },
    };
    let mut total = 0;
    on_event.send(0).unwrap();
    if let Some(update) = update {
        update
            .download_and_install(
                |chunk_length, content_length| {
                    total += chunk_length;

                    if let Some(v) = content_length {
                        let v = (total * 100) as u64 / v;
                        on_event.send(v).unwrap();
                    } else {
                        on_event.send(999).unwrap();
                    }
                },
                || {
                    on_event.send(100).unwrap();
                },
            )
            .await
            .map_err(|e| e.to_string())?;

        app.restart();
    }

    Ok(())
}
